<template>
  <!--Dialog-->
  <Dialog v-model="modelValue">
    <el-form
      :status-icon="true"
      :model="updateForm"
      :inline="true"
      label-width="auto"
      ref="updateFormRef"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item
            label="所属组织"
            prop="organizationId"
            :rules="[{ required: true, message: '请选择所属组织' }]"
          >
            <OrganizationSelect
              v-model="updateForm.organizationId"
              @change="onsetSelectedNode"
              placeholder="请选择所属组织"
              style="width: 256px"
            />
          </el-form-item>
          <el-form-item
            label="帐号"
            prop="userName"
            :rules="[{ required: true, message: '请输入帐号' }]"
          >
            <el-input
              v-model="updateForm.userName"
              placeholder="请输入帐号"
              maxlength="256"
              style="width: 256px"
            />
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input
              v-model="updateForm.password"
              type="password"
              show-password
              placeholder="请输入密码"
              maxlength="256"
              style="width: 256px"
            />
          </el-form-item>
          <el-form-item label="姓" prop="surname">
            <el-input
              v-model="updateForm.surname"
              placeholder="请输入姓"
              maxlength="256"
              style="width: 256px"
            />
          </el-form-item>
          <el-form-item label="名" prop="name">
            <el-input
              v-model="updateForm.name"
              placeholder="请输入名"
              maxlength="256"
              style="width: 256px"
            />
          </el-form-item>
          <el-form-item
            label="邮箱"
            prop="email"
            :rules="[{ required: true, message: '请输入邮箱' }]"
          >
            <el-input
              v-model="updateForm.email"
              placeholder="请输入邮箱"
              maxlength="256"
              style="width: 256px"
            />
          </el-form-item>
          <el-form-item
            label="手机"
            prop="phoneNumber"
            :rules="[{ required: true, message: '请输入手机' }]"
          >
            <el-input
              v-model="updateForm.phoneNumber"
              placeholder="请输入手机"
              maxlength="20"
              style="width: 256px"
            />
          </el-form-item>
          <el-form-item
            label="是否活跃"
            prop="isActive"
            :rules="[{ required: true, message: '请选择是否活跃' }]"
          >
            <el-switch v-model="updateForm.isActive" />
          </el-form-item>
          <el-form-item
            label="是否启用账户锁定"
            prop="lockoutEnabled"
            :rules="[{ required: true, message: '请选择账户锁定' }]"
          >
            <el-switch v-model="updateForm.lockoutEnabled" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item
            label="所属角色"
            prop="roleNames"
            :rules="[{ required: true, message: '请选择角色' }]"
          >
            <RoleSelect v-model="updateForm.roleNames" :min="1" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <el-button type="primary" @click="onSavue(updateFormRef)" :loading="isLoading"
        >保存</el-button
      >
      <el-button @click="onClose">关闭</el-button>
    </template>
  </Dialog>
</template>

<script setup lang="ts">
import { OrganizationSelect } from '@/views/base/organization/select/index';
import { RoleSelect } from '@/views/base/role/select/index';
import { updateAsync, getAsync } from '@/utils/api/user/index';
import { Dialog } from '@/components/dialog/index';
import { propTypes } from '@/utils/propTypes';
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import type { FormInstance } from 'element-plus';
import type { UserUpdateDto } from '@/utils/api/user/type';
import type { ValidateFieldsError } from 'async-validator/dist-types';

// id
const props = defineProps({
  id: propTypes.string
});

let $emit = defineEmits(['update:refresh']);
// 刷新父组件
const refresh = () => {
  $emit('update:refresh');
};

// 组件挂载完成
onMounted(async () => {
  const user = await getAsync(props.id);
  updateForm.value.userName = user.userName;
  updateForm.value.surname = user.surname;
  updateForm.value.name = user.name;
  if (user.organizationId) {
    updateForm.value.organizationId = user.organizationId;
  }
  updateForm.value.isActive = user.isActive;
  updateForm.value.lockoutEnabled = user.lockoutEnabled;
  updateForm.value.email = user.email;
  updateForm.value.phoneNumber = user.phoneNumber;
  updateForm.value.roleNames = user.roleNames;
});

// 组织选择后的业务逻辑
const onsetSelectedNode = (val: any) => {
  updateForm.value.organizationId = val[val.length - 1];
};

// 控制组件隐藏与显示
const modelValue = defineModel<boolean>(propTypes.bool.def(false));
const close = () => {
  modelValue.value = false;
};
// 保存Loading效果状态
const isLoading = ref<boolean>(false);

// 关闭
const onClose = () => {
  //触发自定义事件
  close();
};

// 保存
const onSavue = async (formEl: FormInstance | undefined): Promise<void> => {
  if (!formEl) {
    return;
  }

  // 提交验证
  await formEl.validate(
    async (isValid: boolean, invalidFields?: ValidateFieldsError): Promise<void> => {
      if (isValid) {
        try {
          isLoading.value = true;

          await updateAsync(props.id, updateForm.value);

          // 关闭弹窗
          close();

          // 提示成功
          ElMessage({
            showClose: true,
            message: '修改成功',
            type: 'success'
          });

          // 刷新父组件
          refresh();
        } catch (error) {
          if (error) {
            let msg: string = (error as Error).message;
            if (msg) {
              ElMessage({
                showClose: true,
                message: (error as Error).message,
                type: 'error'
              });
            }
          }
        } finally {
          isLoading.value = false;
        }
      } else {
        console.log('error submit!', invalidFields);
      }
    }
  );
};

// 组件实例
const updateFormRef = ref<FormInstance>();
// 修改对象
const updateForm = ref<UserUpdateDto>({
  userName: '',
  organizationId: '',
  email: '',
  phoneNumber: '',
  isActive: false,
  lockoutEnabled: false,
  roleNames: [],
  password: '',
  concurrencyStamp: ''
});
</script>
<style scoped lang="scss"></style>
